package com.fy56.platform.logistics.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.fy56.platform.logistics.common.BaseController;
import com.fy56.platform.logistics.common.ResultModel;
import com.fy56.platform.logistics.common.ResultStatus;
import com.fy56.platform.logistics.model.Company;
import com.fy56.platform.logistics.model.News;
import com.fy56.platform.logistics.model.Order;
import com.fy56.platform.logistics.service.web.IMiniProgramService;
import com.fy56.platform.logistics.service.web.INewsService;
import com.fy56.platform.logistics.service.wx.*;
import com.fy56.platform.logistics.utils.*;
import com.google.common.collect.Maps;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * 新聞消息controller
 * Created by chen on 2018-05-10.
 */
@SuppressWarnings("ALL")
@RestController
@RequestMapping("/controller/order")
public class OrderController extends BaseController {

    private static Logger log = Logger.getLogger(OrderController.class);
    @Autowired
    private IOrderService iOrderService;
    @Autowired
    private WithdrawMoneyService withdrawMoneyService;
    @Autowired
    private ICompanyInfoService iCompanyInfoService;
    @Autowired
    private IPayOrderService iPayOrderService;
    @Autowired
    private IMiniProgramService iMiniProgramService;
    @Autowired
    private IVipService iVipService;

    @RequestMapping(value = "/synchronizationOrder", method = RequestMethod.POST)
    @ResponseBody
    public ResponseEntity synchronizationOrder(String keyIds, HttpServletRequest request) {
        ResultModel resultModel = ResultModel.ok();
        String errorMessage = "";
        String successMesage = "";
        try{
            if (keyIds != null && keyIds.length() != 0) {
                String[] strList = keyIds.split(",");
                for (int i = 0; i < strList.length; i++) {
                    if (strList[i] != null && strList[i].length() != 0) {
                        Order order = iOrderService.selectByPrimaryKey(Long.parseLong(strList[i]));
                        if (order != null && "1".equals(order.getUploadFlag())) {
                            errorMessage += "id" + strList[i] + "已经同步成功.";
                        }else{
                            long start = System.currentTimeMillis();
                            log.info("补传订单系统数据开始：" + start);
                            String resultF6Order = syncPreOrder(order, "add");
                            if ("SUCCESS".equals(resultF6Order)) {
                                order.setUploadFlag("1");
                                order.setUploadTime(new Date());
                                iOrderService.updateUploadFlag(order);//updateUploadFlag
                            }else{
                                successMesage+="id" + strList[i] + "同步失败"+resultF6Order+".";
                            }
                            log.info(resultF6Order);
                            log.info("补传订单系统数据结束：用时" + (System.currentTimeMillis() - start));
                        }
                    }
                }
            }
        }catch (Exception e){
            log.error("同步订单失败", e);
        }
        if (errorMessage != null && errorMessage.length() != 0) {
            return new ResponseEntity<>(ResultModel.error(ResultStatus.DELETE_ERR, errorMessage), HttpStatus.OK);
        } else {
            return new ResponseEntity<>(ResultModel.ok(), HttpStatus.OK);
        }
    }
    /**
     * 同步预受理单至BS和F6服务
     *
     * @param order
     */
    private String syncPreOrder(Order order, String operate) {

        String resultR = "";
        //如果是F6系统，则不同步数据
        Company company = iCompanyInfoService.getCompanyByCode(order.getTenantCode());
        if (company == null || StringUtil.isEmpty(company.getUrl())) {
            throw new NullPointerException("未设置租户信息");
        }
        //初始化请求参数
        Map<String, String> postParams = Maps.newHashMap();

        //BS同步数据地址
        String url = company.getUrl() + "/preAcceptOrder/syncPreOrder";

        //F6同步数据地址
        if (StringUtil.isNotEmpty(company.getF6AccountSet()) && StringUtil.isNotEmpty(company.getF6OrganizationCode())) {
            url = company.getUrl() + "/orderBill/" + operate + "?databaseId=" + company.getF6AccountSet() + "&organizationCode=" + company.getF6OrganizationCode();
        }
        postParams.put("data", JSONObject.toJSONString(order, SerializerFeature.WriteMapNullValue));
        String result = HttpAsyncUtil.asyncPost(url, postParams, HttpUtil.setHeader());
        if (StringUtil.isNotEmpty(result)) {
            ResultModel model = JSON.parseObject(result, ResultModel.class);
            if (200 == model.getCode()) {
                if ("SUCCESS".equals(model.getMsg())) {
                    resultR = "SUCCESS";
                    log.info("同步业务系统数据成功");
                } else {
                    log.info("同步业务系统数据失败，原因：" + model.getMsg());
                }
            } else {
                log.info("同步业务系统数据失败，原因：请求BS，F6服务端出错！");
            }
        }
        return resultR;
    }




}
